import { ref } from 'vue'
import { adapter, request } from '@/request'
import is from '@/utils/is'
import { message } from 'ant-design-vue'
import { orderKeywordByGet } from '@/core/api/order'
import type { RequestWrapper } from '@/core/interfaces/common'
import type { PlatformEnum } from '@/core/enums/platform'
import type { Order } from '@/core/interfaces/order'
import type { WordTypeEnum } from '@/core/enums/type'
import type { PriceSheet } from '@/core/interfaces/priceSheet'

interface Params {
  orderId: Order['id']
}

export interface RawKeywordData {
  clientType: PlatformEnum
  heatRate: number
  priceAskId: PriceSheet['id']
  id: number
  name: string
  showReasons: string
  type: WordTypeEnum
}

export interface KeywordData extends RawKeywordData {
  frontKey: string
  selected: boolean
  reasons: string[]
  loading?: boolean
}

export default function getOrderKeyword() {
  const service = adapter<RequestWrapper<RawKeywordData[]>>(request)
  const loading = ref(false)
  const response = ref<KeywordData[]>([])

  const fetch = (params: Params) => {
    const { url, method } = orderKeywordByGet()
    loading.value = true

    return service({
      config: {
        url,
        method,
        params
      },
      callback: (res) => {
        response.value = res.data.data.map((item) => {
          return {
            ...item,
            frontKey: `${item.name}|-|${item.clientType}`,
            selected: false,
            reasons: item.showReasons ? item.showReasons.split(',') : []
          }
        })
      },
      error: (err) => {
        if (is.error(err)) {
          message.error(err.message)
        }
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}
